package life.huangzhi.community.community.provider;

import com.alibaba.fastjson.JSON;
import life.huangzhi.community.community.dto.AccessTokenDTO;
import life.huangzhi.community.community.dto.GitHubUser;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 *
 *通过okHttp执行post请求
 * @author Administrator
 * @date 2019/11/25 22:25
 */

@Component//仅仅初始到spring上下文；（注解之后不用初始化对象，IOC）
public class GitHubProvider {
    /**携带信息（accessTokenDTO）获取access_token*/
    public String getAccessToken(AccessTokenDTO accessTokenDTO){
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();
        //包含有第二次请求access_token码所需的参数
            RequestBody body = RequestBody.create(mediaType,JSON.toJSONString(accessTokenDTO));
            //第二次请求的地址+参数传入
            Request request = new Request.Builder()
                    .url("https://github.com/login/oauth/access_token")
                    //https://gitee.com/api/v5/repos/1/1/stargazers
                    .post(body)
                    .build();
            try (Response response = client.newCall(request).execute()) {
                String string = response.body().string();
/*
               access_token= eb2d5d09609b3cc4e1798c0ec9f9c707ad65594a
                        &scope=user
                        &token_type=bearer
*/
                String token = string.split("&")[0].split("=")[1];
                System.out.println(string);
                return token;
        } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
    }
    /**通过access_Token获取到GitHubUser(用户信息)*/
    public GitHubUser getUser(String accessToken){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://api.github.com/user?access_token="+accessToken)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            //将string的json对象解析为一个User对象
            GitHubUser gitHubUser = JSON.parseObject(string, GitHubUser.class);
            return gitHubUser;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
